const { sign, verify } = require('jsonwebtoken')
const { privateKey } = require('../config')
const db = require('../db')

/** TOKEN字段 */
const field = 'Bearer '

const { DefaultContext, DefaultState, ParameterizedContext } = require('koa')
const Router = require('@koa/router')
module.exports = {
  /**
   * @param {ParameterizedContext<DefaultState, DefaultContext & Router.RouterParamContext<DefaultState, DefaultContext>, any>} ctx
   */
  async getUser(ctx) {
    const { authorization } = ctx.request.headers
    if (typeof authorization !== 'string') return false
    const si = authorization.indexOf(field)
    if (si === -1) return false
    let token
    const ei = authorization.indexOf(' ', si + field.length)
    if (ei === -1) {
      token = authorization.slice(si + field.length)
    } else {
      token = authorization.slice(si + field.length, ei)
    }
    try {
      const { id } = verify(token, privateKey)
      const user = await db.first({
        field: ['id', 'username', 'mail', 'portrait', 'power'],
        form: 'user',
        where: {
          id,
        },
      })
      return { ...user }
    } catch {
      return false
    }
  },
  getToken(user) {
    return sign(
      {
        ...user,
        date: Date.now(),
      },
      privateKey,
      { expiresIn: '7d' }
    )
  },
}
